package com.hstc.dao;

import com.hstc.db.DbFactory;
import com.hstc.pojo.Status;
import com.hstc.pojo.Users;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @auther 倪万佳
 * @date 2018/11/12 12:14
 * 邮件状态查询
 */
public class StatusDAO {


    //通过username查找uid
    public Status getStatus(Status status, Connection conn)
    {

        String sql = "select uid,seen from status where username = ? and uid = ?" ;
        ResultSet rs = null;
        PreparedStatement preparedStatement = null;
        Status status1 = null;
        try {
            preparedStatement = conn.prepareStatement(sql);
            preparedStatement.setString(1,status.getUsername());
            preparedStatement.setString(2,status.getUid());
            rs = preparedStatement.executeQuery();
            if(rs.next()){
                String uid = rs.getString(1);
                Integer seen = rs.getInt(2);
                status1 = new Status(uid, seen);
            }

        }
        catch (SQLException e)
        {
            e.printStackTrace();
        }
        finally
        {
            DbFactory.closeAll(rs,preparedStatement, conn);
        }
        return status1;
    }

    //添加uid
    public boolean addUid(Status status, Connection connection) {
        String sql = "insert into status(username,uid) values(?,?)";
        int num = -1;
        PreparedStatement preparedStatement = null;
        try {
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1,status.getUsername());
            preparedStatement.setString(2,status.getUid());

            num = preparedStatement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally
        {
            DbFactory.closeAll(null,preparedStatement, connection);
        }

        if(num != -1) {
            return true;
        }else {
            return false;
        }
    }

    public boolean updateSeen(Status status, Connection connection) {
        String sql = "update status set seen = ? where username = ? and uid = ? ";
        int num = -1;
        PreparedStatement preparedStatement = null;
        try {
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1,status.getSeen());
            preparedStatement.setString(2,status.getUsername());
            preparedStatement.setString(3,status.getUid());
            preparedStatement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally
        {
            DbFactory.closeAll(null,preparedStatement, connection);
        }
        return true;
    }

}
